import axios from "../network/index"
Page({
  /**
   * 页面的初始数据
   */
  data: {
    testSrc: "http://tiebapic.baidu.com/forum/w%3D580%3B/sign=97a072b96bd98d1076d40c391104b90e/8cb1cb13495409236429873b8558d109b3de4937.jpg",
    datas: {},
    showDetail: false,
    orderNo: "",
    currentIndex: "",
    currentProject: {},
    allocationData: [],
    currentType: "",
    isAgain: false,
    showCheck: false,
  },
  _confirm(e) {
    let type = e.currentTarget.dataset.type
    this.setData({
      currentType: type
    })
    let str = type == 1 ? '确认申请' : type == 2 ? '发货' : '验收'
    wx.showModal({
      title: '温馨提示',
      content: `您是否确定进行${str}操作？`,
      success: res => {
        if (res.confirm) {
          this.confirmFnc(type)
        }
      }
    })
  },
  confirmFnc(type, noStock) {
    let url = ""
    let data = {
      demandApplyNo: this.data.orderNo,
      memo: '',
      userId: wx.getStorageSync('userId')
    }
    let appli = ''
    switch (type) {
      case '1':
        url = "/demandApply/confirm"
        break;
      case '2':
        data['allocationData'] = this.data.allocationData
        if (noStock == 1) data['confirmSubmit'] = true
        url = "/demandApply/delivery"
        break;
      case '3':
        url = "/demandApply/receivingGoods"
        break;
    }
    if (type == 2) appli = "application/json"
    wx.showLoading({
      title: '加载中...',
    })
    axios({
      url,
      method: "post",
      data
    }, appli).then(res => {
      wx.hideLoading()
      if (res.code == 200) {
        if (type == 2 && this.data.isAgain) { //如果是发货并自动生成报销单之后的状态
          wx.redirectTo({
            url: '/pages/Taskdetail/lindex?code=' + res.data,
          })
          return
        }
        wx.showToast({
          title: res.msg,
          duration: 1500
        })
        wx.navigateBack({
          delta: 1,
        })
      } else {
        if (res.code == 300) { //如果库存不足
          wx.showModal({
            title: '温馨提示',
            content: res.msg || '请求错误',
            success: v => {
              if (v.confirm) {
                this.confirmFnc(this.data.currentType, 1)
                this.setData({
                  isAgain: true
                })
              } else {
                this.setData({
                  isAgain: false
                })
              }
            }
          })
        } else {
          wx.showModal({
            showCancel: false,
            title: "温馨提示",
            content: res.msg
          })
          this.setData({
            isAgain: false
          })
        }
      }
    }).catch(() => {
      wx.hideLoading()
    })
  },
  allocaIpt(e) {
    let val = e.detail
    let currentProject = this.data.currentProject
    this.setData({
      'currentProject.allocationNum': val
    })
  },
  checkIpt(e) {
    let val = e.detail
    let currentProject = this.data.currentProject
    this.setData({
      'currentProject.checkNum': val
    })
  },
  //调拨
  allocaBtn() {
    let allocationData = this.data.allocationData
    let currentProject = this.data.currentProject
    let datas = this.data.datas
    let currentIndex = this.data.currentIndex
    if (currentProject.allocationNum < 1) {
      wx.showToast({
        title: '调拨数量不可为0',
        icon: "none"
      })
      return
    }
    if (parseInt(currentProject.allocationNum) > parseInt(currentProject.stockNum)) {
      wx.showToast({
        title: '调拨数量不可大于库存数量',
        icon: "none"
      })
      return
    }
    allocationData.push({
      materialCode: currentProject.materialCode,
      num: currentProject.allocationNum
    })
    this.setData({
      [`datas.materialData[${currentIndex}]`]: currentProject,
      allocationData,
      showDetail: false
    })
  },
  //单个验收
  sendCheck() {
    let currentProject = this.data.currentProject
    console.log(currentProject);
    if (currentProject.checkNum < 1) {
      wx.showToast({
        title: '验收数量不可为0',
        icon: "none"
      })
      return
    }
    if (parseInt(currentProject.checkNum) > parseInt(currentProject.num)) {
      wx.showToast({
        title: '验收数量不可大于申请数量',
        icon: "none"
      })
      return
    }
    wx.showLoading({
      title: '加载中...',
    })
    axios({
      url: '/demandApply/receivingGoods',
      method: "post",
      data: {
        demandApplyNo: this.data.orderNo,
        userId: wx.getStorageSync('userId'),
        materialData: [{
          materialCode: currentProject.materialCode,
          num: currentProject.checkNum
        }]
      }
    },'application/json').then(res => {
      wx.hideLoading()
      if (res.code == 200) {
        wx.showToast({
          title: res.msg,
        })
        this.getDetail()
        this.closeCheck()
      }
    }).catch(() => {
      wx.hideLoading()
    })



  },
  // 图片预览
  prevImg(e) {
    let list = this.data.datas.materialData
    let index = e.currentTarget.dataset.index
    if (!list[index].icon) {
      wx.showToast({
        title: '暂无图片',
        icon: "none"
      })
      return
    }
    let urls = list.map(item => item.icon)

    wx.previewImage({
      current: list[index].icon,
      urls
    })
  },
  //附件预览
  prevImgs(e) {
    let list = this.data.datas.imgs
    let current = e.currentTarget.dataset.image
    let urls = list.map(item => item.url)
    wx.previewImage({
      current,
      urls
    })
  },
  openDetail(e) {
    let currentProject = e.currentTarget.dataset.item
    let index = e.currentTarget.dataset.index
    this.setData({
      showDetail: true,
      currentProject,
      currentIndex: index
    })
  },
  openCheck(e) {
    let currentProject = e.currentTarget.dataset.item
    let index = e.currentTarget.dataset.index
    this.setData({
      showCheck: true,
      currentProject,
      currentIndex: index
    })
  },
  closeDetail() {
    this.setData({
      showDetail: false
    })
  },
  closeCheck() {
    this.setData({
      showCheck: false
    })
  },
  getDetail() {
    wx.showLoading({
      title: '加载中...',
    })
    axios({
      url: '/demandApply/detail',
      method: "post",
      data: {
        orderNo: this.data.orderNo,
        userId: wx.getStorageSync('userId'),
      }
    }).then(res => {
      wx.hideLoading()
      if (res.code == 200) {
        let users = res.data.confirmUserData
        let userNames = ''
        if (users && users.length > 0) {
          userNames = users.map(item => item.name).toString()
        }
        this.setData({
          datas: res.data,
          userNames,
        })

      }
    }).catch(() => {
      wx.hideLoading()
    })
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      orderNo: options.orderNo
    })
    this.getDetail()
  },




  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {


  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {}
})